<template>
  <div>
    <div>
      <el-row>
        <el-col :span="6">
          <el-button @click="showDialog">新增</el-button>
        </el-col>
        <el-col :span="6">
          <a href="/api/file/goods.xlsx">下载模板</a>
        </el-col>
        <el-col :span="6">
          <el-button @click="down">点击下载模板</el-button>
          <el-button @click="downGoods">导出所有商品</el-button>
        </el-col>
        <el-col :span="6"
          ><div class="grid-content ep-bg-purple item">
            <div class="filebtn">批量新增</div>

            <input type="file" accept=".xlsx" class="file" @change="change" />
          </div>
        </el-col>
      </el-row>

      <el-dialog v-model="dialogVisible" title="新增商品" width="30%" :before-close="handleClose">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          status-icon
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-form-item label="商品类别" prop="typeid">
            <el-select
              v-model="ruleForm.typeid"
              class="m-2"
              placeholder="请选择商品类别"
              size="large"
            >
              <el-option
                v-for="item in typeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="商品名称" prop="name">
            <el-input v-model="ruleForm.name" />
          </el-form-item>

          <el-form-item label="商品尺寸" prop="size">
            <el-input v-model="ruleForm.size" />
          </el-form-item>

          <el-form-item label="图片">
            <el-upload
              v-model:file-list="fileList"
              ref="uploadRef"
              class="upload-demo"
              action="/api/uploads"
              :auto-upload="false"
              :limit="9"
              :on-success="success"
              name="filename"
            >
              <template #trigger>
                <el-button type="primary">select file</el-button>
              </template>

              <template #tip>
                <div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">新增</el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <el-table :data="goodsList" style="width: 100%">
      <el-table-column label="类别名称">
        <template #default="scope">
          {{ scope.row.typeid.type }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="size" label="商品尺寸" />
      <el-table-column label="图片">
        <template #default="scope">
          <div class="demo-image__preview">
            <span v-if="scope.row.img[0].indexOf('http') != -1">
              <el-image
                z-index="10000"
                :preview-teleported="teleported"
                style="width: 100px; height: 100px"
                :src="scope.row.img[0]"
                :zoom-rate="1.2"
                :preview-src-list="scope.row.img"
                :initial-index="4"
                fit="cover"
              />
            </span>
            <el-image
              v-else
              z-index="10000"
              :preview-teleported="teleported"
              style="width: 100px; height: 100px"
              :src="'api/' + scope.row.img[0]"
              :zoom-rate="1.2"
              :preview-src-list="scope.row.img.map((item:any)=>'api/'+item)"
              :initial-index="4"
              fit="cover"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="delByItem(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { goodsAdd, goodsQuery, goodsDel, goodsAddMany } from '../service/goodsService'
import { typeinfoQuery } from '../service/typeinfoService'
import { importsExcel, exportExcel } from '../utils/excel'
import type { FormInstance, FormRules, UploadInstance, UploadUserFile } from 'element-plus'
const uploadRef = ref<UploadInstance>()
const ruleFormRef = ref<FormInstance>()
const fileList = ref<UploadUserFile[]>([]) //需要上传图片的集合
const successList = ref<any>([]) //上传成功的图片的集合
const typeList = ref<any>([]) //类别类别
const goodsList = ref<any>([]) //商品数据集合
const teleported = ref(true)

let change = async (e: any) => {
  //文件选择
console.log(e);
  let res = await importsExcel(e) //文件
  let list = res.map((item: any) => {
    return {
      name: item.商品名称,
      size: item['商品尺寸'],
      img: item['商品图片'].split(','),
      type: item['商品类型']
    }
  })
  let res2 = await goodsAddMany({ list })

  console.log(res2)
}

onMounted(async () => {
  let res = await goodsQuery({})
  console.log(res)
  if (res.data.code == 200) {
    goodsList.value = res.data.list
  }
})
const down = () => {
  //下载
  setTimeout(() => {
    //一秒以后执行代码
    let url = '/file/goods.xlsx' //文件地址
    let a = document.createElement('a')
    a.href = 'api/' + url
    a.click() //a标签被点击
    a.remove() //消失
  }, 1000)
}
const downGoods = async () => {
  await exportExcel(
    [
      { dataIndex: '_id', key: '_id', title: '编号' },
      { dataIndex: 'name', key: 'name', title: '商品名称' },
      { dataIndex: 'size', key: 'size', title: '尺寸' },
      { dataIndex: 'type', key: 'type', title: '类别' },
      { dataIndex: 'img', key: 'img', title: '图片' }
    ],
    goodsList.value.map((item:any)=>{
      item.type = item.typeid.type
      return item;
    }),
    '2118班商品信息.xlsx'
  )
}
//外键
const delByItem = async (info: any) => {
  //console.log(info);
  let { _id } = info
  let result = await goodsDel({ id: _id })
  goodsList.value = goodsList.value.filter((item: any) => item._id !== _id)
}
const success = async (res: any) => {
  // console.log(res);
  if (res.code == 200) {
    //图片上传成功
    successList.value.push(res.url)
    if (successList.value.length === fileList.value.length) {
      //全部上传成功
      let result = await goodsAdd({
        typeid: ruleForm.typeid,
        name: ruleForm.name,
        size: ruleForm.size,
        img: successList.value
      })
      console.log(result)
      if (result.data.code === 200) {
        //新增成功
        resetForm(ruleFormRef.value as any) //
        console.log(result.data)

        goodsList.value = [...goodsList.value, ...result.data.data]
      }
    }
  }
}

const submitUpload = () => {
  //手动上传图片的事件
  uploadRef.value!.submit()
}

let dialogVisible = ref<boolean>(false)
const handleClick = () => {
  console.log('click')
}
const showDialog = async () => {
  dialogVisible.value = true
  let res = await typeinfoQuery({})
  if (res.data.code == 200) {
    //表示有数据
    typeList.value = res.data.list.map((item: any) => {
      return {
        value: item._id,
        label: item.type
      }
    })
  }
}

const ruleForm = reactive({
  typeid: '',
  name: '',
  size: ''
})
const rules = reactive<FormRules>({
  typeid: [{ required: true, message: '不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  size: [{ required: true, message: '尺寸不能为空', trigger: 'blur' }]
})

const submitForm = (formEl: FormInstance | undefined) => {
  //表单提交事件
  if (!formEl) return
  formEl.validate((valid: any) => {
    if (valid) {
      if (fileList.value.length) {
        //判断集合的长度
        submitUpload() //图片上传
      } else {
        alert('请选择图片')
      }

      //表示验证通过
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields() //表单内容重置
  fileList.value = [] //清空 选择的图片
  dialogVisible.value = false //dialog关闭
}
</script>
<style>
.item {
  position: relative;
}
.filebtn {
  position: absolute;
  left: 0;
  background-color: #409eff;
  color: white;
  width: 100px;
  text-align: center;
  line-height: 30px;
  border-radius: 5px;
}
.file {
  border: 1px solid red;
  z-index: 9999;
  opacity: 0;
  width: 100px;
}
</style>
